<template>
  <menu-bar v-if="!isInElectronBrowser()"></menu-bar>
  <div class="center" :class="{ mt20: !isInElectronBrowser() }">
    <el-card class="page">
      <template #header> Electron-Vite-Vue 模板 </template>
      <ProjectCreator></ProjectCreator>
      <div class="mb-20">
        <el-divider> 可用由下列网址访问网站 </el-divider>
        <div v-for="(href, i) in linkHref" :key="i">
          <el-button text type="primary" @click="openExternal(href)">
            {{ href }}
          </el-button>
        </div>
      </div>
      <div v-if="isInElectronBrowser()" class="flex-around">
        <el-button @click="killApp">终止服务器</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { ElMessageBox } from "element-plus";
import { computed, ref } from "vue";
import type ERemote from "@electron/remote";
document.title = "Electron-Vite-Vue 模板";

function isInElectronBrowser() {
  try {
    const eRemote = require("@electron/remote") as typeof ERemote;
    eRemote.getCurrentWindow();
    return true;
  } catch (error) {
    return false;
  }
}
let ips = ref<string[]>((await axios.get("/api/get-ips")).data);
let port = ref<string>(window.location.port);

let linkHref = computed(() => {
  return ips.value.map((ip) => {
    return port.value ? `http://${ip}:${port.value}` : `http://${ip}`;
  });
});

function openExternal(href: string) {
  try {
    let electron = require("electron");
    electron.shell.openExternal(href);
  } catch (error) {
    window.open(href, "_blank");
  }
}

function killApp() {
  let { ipcRendererSync } = require("albert.gao/default/electron-renderer");
  ElMessageBox({
    type: "warning",
    title: "提示",
    message: "确认终止服务器？",
    showCancelButton: true,
    showClose: true,
  })
    .then(() => {
      return ipcRendererSync("kill-app", {});
    })
    .catch(() => {});
}
</script>

<style lang="scss" scoped>
.page {
  width: 500px;
  height: 500px;
}
.mb-20 {
  margin-bottom: 20px;
}
.flex-around {
  display: flex;
  justify-content: space-around;
}

.mt20 {
  margin-top: 20px;
}
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
